package com.aaa.demo06;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ${崔灿}
 * @date 2022/11/01 15:54
 **/

public class TestSafe_Lock {
    private static String [] arr =new String[2];
    private static int index = 0;
    private static Object lock= new Object();
    public static void main(String[] args) throws InterruptedException {
        //创建锁对象
        Lock lock = new ReentrantLock();
        //构造函数中可以以线程提供任务对象Runable
        //匿名实现类
        Thread t1 = new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    //加锁
                lock.lock();
                    if(arr[index]==null){
                        arr[index] = "hello";
                        index++;
                    }
                } finally {
                    lock.unlock();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
               try {
                   //加锁
                   lock.lock();
                    if (arr[index] == null) {
                        arr[index] ="world";
                        index++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        });

        t1.start();
        t2.start();
        //不能直接打印arr，因为main线程可能先获取cpu
        t1.join();
        t2.join();
        System.out.println(Arrays.toString(arr));
    }
}
